package com.srwl.mytx.adapter;

import android.content.Context;
import android.content.Intent;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.activity.MessageRecordActivity;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.im.conversation.Conversation;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.MoonUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.BottomBarBadge;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class LocalSearchAdapter extends RecyclerView.Adapter<LocalSearchAdapter.ViewHolder> {
    private static final String TAG = "LocalSearchAdapter";

    private Context context;
    private List<Conversation> conversationList;
    private InteractionListener listener;
    private List<String> idList = new ArrayList<>();//需要下载用户信息的id列表

    public LocalSearchAdapter(Context context, List<Conversation> conversationList) {
        this.context = context;
        this.conversationList = conversationList;
    }

    public LocalSearchAdapter(Context context, List<Conversation> conversationList, InteractionListener mOnItemClickListener) {
        this.context = context;
        this.conversationList = conversationList;
        this.listener = mOnItemClickListener;
    }


    public void setOnItemClickListener(InteractionListener mOnItemClickListener) {
        this.listener = mOnItemClickListener;
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.ease_row_chat_history, parent, false);
        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {

        Conversation conversation = conversationList.get(position);
        //会话是对方的用户id
        String userId = conversation.getCId();
        // TODO: 2019/8/28 会话表和用户表应该 做成关联表
        User targetUser = conversation.getToUser();

        if (targetUser == null) {
            targetUser = Helper.getInstance().getContactUserInfo(conversation.getCId());
            if (targetUser != null) {
                conversation.setToUser(targetUser);
            } else {
                if (!idList.contains(userId)) {
                    idList.add(userId);
                    // 从服务端获取联系人信息
                    getUserInfo(holder, userId);
                }
            }
        }
        if (targetUser != null) {
           // Glide.with(context).load(targetUser.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.tx_default_avatar).into(holder.iv_avatar);
            GlideLoadUtils.glideLoad(context,targetUser.getAvatar(),holder.iv_avatar,R.drawable.tx_default_avatar_1);
            SpannableString spannableString = MoonUtils.replaceEmoticonsAndHighlight(context, targetUser.getUsername(), 0.06f, ImageSpan.ALIGN_BOTTOM, targetUser.getHighlightKeyWord(), context.getResources().getColor(R.color.holo_blue_bright));
            holder.tv_name.setText(spannableString);
        }
        holder.motioned.setVisibility(View.GONE);


        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (listener != null) {
                    listener.onLongClick(position, conversation);
                    return true;
                }
                return false;
            }
        });


        if (conversation.getUnReadCount() > 0) {
            holder.tv_unreadCount.setText(String.valueOf(conversation.getUnReadCount()));
            holder.tv_unreadCount.show();
        } else {
            holder.tv_unreadCount.hide();
        }

        ArrayList<Message> messageList = (ArrayList<Message>) conversation.getMessageList();
        int size = messageList.size();
        if (size > 1) {
            String tips = "找到" + size + "条匹配消息";
            SpannableString spannableString = MoonUtils.replaceEmoticonsAndHighlight(context, tips, 0.06f, ImageSpan.ALIGN_BOTTOM, String.valueOf(size), context.getResources().getColor(R.color.text_black));
            holder.tv_message.setText(spannableString);
        } else if (size == 1) {
            Message lastMessage = messageList.get(0);

            if (lastMessage == null) {
                Log.e(TAG, "onBindViewHolder:lastMessage为空 ");
                return;
            }
            //  MoonUtils.identifyFaceExpression(context, holder.tv_message, lastMessage.getContent(), ImageSpan.ALIGN_BOTTOM, 0.6f);
            SpannableString spannableString = MoonUtils.replaceEmoticonsAndHighlight(context, lastMessage.getContent(), 0.06f, ImageSpan.ALIGN_BOTTOM, lastMessage.getHighlightKeyWord(), context.getResources().getColor(R.color.holo_blue_bright));
            holder.tv_message.setText(spannableString);
            holder.time.setText(DateUtils.getTimestampString(lastMessage.getCreated()));
            //发送失败，展示红点，用以提示
            if (Utils.isSendMessage(lastMessage) && lastMessage.getSendState() != null && lastMessage.getSendState() == Constant.IM_SEND_STATE_FAIL) {
                holder.msgState.setVisibility(View.VISIBLE);
            } else {
                holder.msgState.setVisibility(View.GONE);
            }
        } else {
            holder.tv_message.setText("没找到匹配的消息");
        }
        User finalTargetUser = targetUser;
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (messageList.size() > 1) {//跳转到消息记录页面，展示多条消息
                    context.startActivity(new Intent(context, MessageRecordActivity.class).putParcelableArrayListExtra("messageList", messageList).putExtra(Constant.EXTRA_TARGET_USER, finalTargetUser));
                    return;
                }
                if (userId.equals(UserProfileManager.getInstance().getLoginUserInfo().getuId()))
                    Snackbar.make(v, R.string.Cant_chat_with_yourself, Snackbar.LENGTH_SHORT).show();
                else {

                    Intent intent = new Intent(context, ChatActivity.class);
                    User targetUser = Helper.getInstance().getContactUserInfo(userId);
                    if (targetUser == null) {
                        return;
                    }
                    intent.putExtra(Constant.EXTRA_TARGET_USER_INFO, targetUser);
                    if (messageList.size() == 1) {
                        intent.putExtra(Constant.EXTRA_INFO_MESSAGE, messageList.get(0));
                    }
                    context.startActivity(intent);
                }
            }
        });

    }


    @Override
    public int getItemCount() {
        return conversationList.size();
    }


    private void getUserInfo(final ViewHolder holder, final String userId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(UserService.class)
                .getUserInfo(userId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        idList.remove(userId);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse:从服务端获取联系人信息出错 " + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse:从服务端获取联系人信息出错 " + result.getMsg());

                            return;
                        }

                        JSONObject object = (JSONObject) result.getData();

                        User user = object.toJavaObject(User.class);
                        user.setUId(userId);
                        user.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(user);//作为临时联系人，保存在用户表中

                        //Glide.with(context).load(user.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.tx_default_avatar).into(holder.iv_avatar);
                        GlideLoadUtils.glideLoad(context,user.getAvatar(),holder.iv_avatar,R.drawable.tx_default_avatar_1);

                        holder.tv_name.setText(user.getUsername());

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        idList.remove(userId);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    public class ViewHolder extends RecyclerView.ViewHolder {

        ImageView iv_avatar;
        TextView tv_name;
        TextView tv_message;
        TextView time;
        BottomBarBadge tv_unreadCount;
        View msgState;
        TextView motioned;

        public ViewHolder(View itemView) {
            super(itemView);
            iv_avatar = itemView.findViewById(R.id.avatar);
            tv_name = itemView.findViewById(R.id.name);
            tv_unreadCount = itemView.findViewById(R.id.unread_msg_number);
            tv_message = itemView.findViewById(R.id.tv_message);
            time = itemView.findViewById(R.id.time);
            msgState = itemView.findViewById(R.id.msg_state);
            motioned = itemView.findViewById(R.id.mentioned);
        }

    }

    public interface InteractionListener {
        void onLongClick(int position, Conversation conversation);
    }

}
